package com.yc.snacknet_vue.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.snacknet_vue.utils.SessionKeys;
import com.yc.snacknet_vue.utils.StringUtil;

/**
 * 过滤后台
 * @author UNO
 * @date 2021年7月31日
 * Email 2759451734@qq.com
 */
//@WebFilter( filterName = "/CheckBackLoginFilter", value = "/back/manager/*",
//			initParams = @WebInitParam(name = "errorPage", value = "back/login.html"))
public class CheckBackLoginFilter implements Filter {
	private String errorPage = "login.html";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String temp = filterConfig.getInitParameter("errorPage");
		if( !StringUtil.checkNull(temp)) {
			errorPage = temp;
		}
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//判断用户有没有登录 -> 如果登录 我们就将登录的信息存到session中
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		//判断是否登录 session是否有值
		if( null == req.getSession().getAttribute(SessionKeys.CURRENTBACKLOGINACCOUNT)) {
			//未登录 跳转到指定姐卖你
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			
			//重定向 resp.sendRedirect(errorPage);  死循环
			
			//2、演示2 b 想办法获取的URL地址 -> 获取的URL地址 + 资源路径
			String basePath = req.getScheme() + ".//" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
			out.print("<script>alert('请先登录...');location.href='" + basePath + errorPage +"';<script>");
			out.flush();//刷新缓冲区
			out.close();//会默认关闭流 可以省略
		}else { //否则 已经登录过的 将所有请求链式调用下一个过滤器
			chain.doFilter(request, response);
		}
	}
}
